package org.university.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.university.entity.Department;
import org.university.repository.DepartmentRepository;
import org.university.service.DepartmentService;

@Service
public class DepartmentServiceImpl extends GenericServiceImpl<Department, Integer> implements DepartmentService {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentServiceImpl.class);
    private final DepartmentRepository departmentRepository;

    public DepartmentServiceImpl(DepartmentRepository repository, DepartmentRepository departmentRepository) {
        super(repository);
        this.departmentRepository = departmentRepository;
    }

    @Override
    public Department save(Department department) {
        Integer id = department.getDeptId();
        logger.info("保存学院ID: {}", id);
        if (id != null && departmentRepository.existsById(id)) {
            throw new IllegalArgumentException("学院ID已存在: " + id);
        }
        return departmentRepository.save(department);
    }

    @Override
    public Page<Department> findAll(Pageable pageable) {
        logger.info("查询所有学院: 分页信息={}", pageable);
        return departmentRepository.findByDeletedFalse(pageable);
    }

    @Override
    public Page<Department> findAll() {
        logger.info("查询所有学院（无分页）");
        return departmentRepository.findByDeletedFalse(Pageable.unpaged());
    }

    @Override
    public void deleteById(Integer id) {
        logger.info("删除学院ID: {}", id);
        departmentRepository.findById(id).ifPresent(department -> {
            department.setDeleted(1);
            departmentRepository.save(department);
        });
    }

    @Override
    public Long getStudentCount(Integer id) {
        // 在Service层调用
        Page<Department> page = departmentRepository.findByDeletedFalse(Pageable.unpaged());
        long totalCount = page.getTotalElements();
        return totalCount;
    }
}